package pic

import (
	"bytes"
	"fmt"
	"io"
	"iot-base/common/dbconn"
	"mime/multipart"
	"net/http"
	"os"
	"sync/atomic"
	"time"
)

type PICInfo struct {
	FileName string    `gorm:"primarykey" json:"file_name"`
	SnapTime time.Time `json:"snap_time"`
	//URI          string    `json:"uri"`
	IpcId       string `json:"ipc_id"`
	IpcName     string `json:"ipc_name"`
	StationName string `json:"station_name"`
	StationID   string `json:"station_id"`
	//ProfileToken string    `json:"profile_token"`
}

func init() {
	dbconn.DBConnection.AutoMigrate(&PICInfo{})
}

//SavePicInfoToDB 存储到数据库中
func SavePicInfoToDB(snapTime time.Time, ipcId, filename, ipcName, stationId, stationName string) PICInfo {
	info := PICInfo{
		FileName:    filename,
		SnapTime:    snapTime,
		IpcId:       ipcId,
		IpcName:     ipcName,
		StationName: stationName,
		StationID:   stationId,
		//URI:          uri,
		//ProfileToken: profileToken,
	}
	dbconn.DBConnection.Create(&info)
	return info
}

var no int64 = 0

func makedir(uid string, year, month, day, hour int) string {
	return fmt.Sprintf("/home/linaro/work/pic/%s/%d/%d/%d/%d", uid, year, month, day, hour)
}
func SavePic(uid, uri, ipcname, stationId, stationname, remoteaddr, token string) (string, error) {
	//var cstZone = time.FixedZone("CST", 8*3600)
	now := time.Now() //.In(cstZone)
	year := now.Year()
	month := now.Month()
	day := now.Day()
	hour := now.Hour()
	sdir := makedir(uid, year, int(month), day, hour)
	os.MkdirAll(sdir, os.ModePerm)
	res, err := http.Get(uri)
	if err == nil {
		defer res.Body.Close()
		atomic.AddInt64(&no, 3)
		filename := fmt.Sprintf("pic_%d_%d_%d", now.Minute(), now.Second(), no)
		//filename = sdir + "/" + filename
		f, errf := os.Create(sdir + "/" + filename)
		if errf != nil {
			return "", errf
		}
		io.Copy(f, res.Body)
		cfilename := fmt.Sprintf("%s@%s-%d-%d-%d-%d", filename, uid, year, month, day, hour)
		fileid := "api/pic/" + cfilename
		//saveDB(now, uid, fileid)
		SavePicInfoToDB(now, uid, fileid, ipcname, stationId, stationname)
		if token != "" && remoteaddr != "" {
			SavePicToCloud(sdir, filename, fileid, remoteaddr, token)
		}

		return fileid, nil

	}
	return "", err

}
func ParseFileName(cfilename string) (dir, filename string, info PICInfo) {
	var uid string
	var year, month, day, hour, min, sec, cno int
	fmt.Sscanf(cfilename, "pic_%d_%d_%d@%s-%d-%d-%d-%d", &min, &sec, &cno, &uid, &year, &month, &day, &hour)
	dir = makedir(uid, year, month, day, hour)
	filename = fmt.Sprintf("pic_%d_%d_%d", min, sec, cno)
	fileid := "api/pic/" + cfilename
	info.FileName = fileid
	var cstZone = time.FixedZone("CST", 8*3600)
	info.SnapTime = time.Date(year, time.Month(month), day, hour, min, sec, 0, cstZone)
	info.IpcId = uid
	return dir, filename, info

}

func SavePicToCloud(dir, filename, fileid, addr, token string) {
	bodyBuffer := &bytes.Buffer{}
	bodyWriter := multipart.NewWriter(bodyBuffer)

	fileWriter, _ := bodyWriter.CreateFormFile("files", fileid)

	file, _ := os.Open(dir + "/" + filename)
	defer file.Close()

	io.Copy(fileWriter, file)

	contentType := bodyWriter.FormDataContentType()

	bodyWriter.Close()
	req, _ := http.NewRequest("GET", addr, bodyBuffer)
	req.Header.Set("api_token", token)
	req.Header.Set("Content-Type", contentType)
	resp, _ := (&http.Client{}).Do(req)
	if resp != nil {
		defer resp.Body.Close()
	}
	/*
	   resp_body, _ := ioutil.ReadAll(resp.Body)

	   log.Println(resp.Status)
	   log.Println(string(resp_body))*/
}
